import gradio as gr
import requests
import sys
import json

def qa_infer(q, context):
    url = f'http://127.0.0.1:7777/qa'
    print(url)
    response = requests.post(url, json={
        'q': q,
        'context': context
    })
    if response.status_code != 200:
        print('Request failed with status code:', response.status_code, file=sys.stderr, flush=True)
        return '<error>', 'An <span style="background-color: green;">Error</span> from the Server!'
    else:
        try:
            res = json.loads(response.text)
            return res['a'], res['html']
        except Exception as ex:
            return '<parsing error>', str(ex)
    

# 构建Gradio界面
with gr.Blocks(analytics_enabled=False) as demo:

    # 输入
    cmp_q = gr.Textbox(interactive=True, label='问题', visible=True, )
    cmp_context = gr.Textbox(interactive=True, label='上下文', visible=True, )

    # 按钮
    cmp_btn = gr.Button('QA', visible=True, )
    
    # output
    cmp_a = gr.Textbox(interactive=False, label='答案', visible=True, )
    cmp_html = gr.HTML()

    cmp_btn.click(qa_infer, [cmp_q, cmp_context], [cmp_a, cmp_html], queue=False)
    
# 使用queue（目前这个例子太简单，没有用到queue，后面会用到。）
demo.queue(
    concurrency_count=10,
    status_update_rate='auto',
    # status_update_rate=0.02,
)

# 启动Gradio
# demo.launch(server_name='0.0.0.0', server_port=port, share=True, debug=False)  # 带内网穿透
demo.launch(server_name='0.0.0.0', server_port=8888, debug=False, inbrowser=False)